﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using RBAC.Web.Mapper;
using RBAC.Web.Models;
using RBAC.Web.Service;
using RBAC.Web.Utilities;

namespace RBAC.Web.Controllers
{
    public class DomainController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ListDomain(int? page, string sort = "", string sortdir = "asc"
                            , String DomainNameSearch = ""
                        )
        {
            //ถ้าตัวมันเป็นลูกของตัวอื่น ต้องทำการ clear ค่า TempData ของแม่ก่อน

            // end clear ค่า TempData

            ListDomainModel model = new ListDomainModel();
            /*GetAllResponseModel<DomainModel> temp = Search(new GetAllDomainRequestModel()
            {
									 DomainName = DomainNameSearch,
						                    Sort = sort,
					SortType = sortdir == "asc" ? sType.ASC : sType.DESC
            });
            model.ListItems = temp.List;*/

            return View(model);
        }

        [HttpPost]
        public ActionResult ListDomain(string submitButton, string[] checkbox, ListDomainModel input)
        {
            if (ModelState.IsValid)
            {
                switch (submitButton)
                {
                    case "Search":
                        input.ListItems = PrepareSearch(input);
                        break;
                    default:
                        break;
                }
            }
            return View(input);
        }

        public ActionResult EditDomain(String DomainName)
        {
            ServiceClient service = new ServiceClient();

            GetAllDomainRequestDto objGet = new GetAllDomainRequestDto()
            {
                EqPk = true,
                DomainName = StringParser.GetValue<String>(DomainName)
            };

            var list = service.GetAllDomain(objGet);
            DomainModel resultModel = null;


            if (list.Data != null && list.Data.Count > 0)
            {
                DomainDto resultDto = list.Data[0];
                resultModel = DomainMapper.DtoToModel(resultDto);

                //Get One-to-many data data ของลูก
                // สร้าง method PrepareXXXSearch

                resultModel.Functions = PrepareFunctions_FunctionSearch(resultModel.Id);
            }

            /**** ถ้ามีลูก gen  *****/
            //One-to-meny store parent's value to send to child
            if (resultModel != null)
            {
                TempData["DomainId"] = resultModel.Id;


                TempData["DomainLookupField"] = resultModel.DomainName;


                TempData["DomainDescField"] = resultModel.Id;
            }

            //One-to-meny operaton message
            if (TempData["FunctionMessage"] != null && TempData["FunctionStatus"] != null)
            {
                ViewData["FunctionMessage"] = TempData["FunctionMessage"];
                ViewData["FunctionStatus"] = TempData["FunctionStatus"];
                if (TempData["FunctionId"] != null)
                    ViewData["FunctionId"] = TempData["FunctionId"];
            }
            /**** end *****/
            SetupRegisterViewModel(resultModel);
            return View(resultModel);
        }

        [HttpPost]
        public ActionResult Update(DomainModel inputModel, String DomainName)
        {
            ImageClass IClass = new ImageClass();
            if (ModelState.IsValid)
            {
                ServiceClient service = new ServiceClient();
                var output = service.UpdateDomain(DomainMapper.ModelToDto(inputModel));
                var listDisplay = PrepareRetrunFromOperation(new ListDomainModel(), output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Edit, output.Status));


                // เพิ่ม message แสดงในหน้าแม่
                TempData["DomainMessage"] = listDisplay.Message;
                TempData["DomainStatus"] = output.Status;
                if (output.Data != null)
                {
                    TempData["DomainId"] = output.Data.Id;
                }
                return View("ListDomain", listDisplay);
            }
            else
            {
                //Get One-to-many data data ของลูก
                // สร้าง method PrepareXXXSearch

                inputModel.Functions = PrepareFunctions_FunctionSearch(inputModel.Id);
                SetupRegisterViewModel(inputModel);
                return View("EditDomain", inputModel);
            }
        }

        public ActionResult Add()
        {
            DomainModel model = new DomainModel();
            SetupRegisterViewModel(model);


            return View("AddDomain", model);
        }

        [HttpPost]
        public ActionResult AddDomain(DomainModel inputModel)
        {
            ImageClass IClass = new ImageClass();
            if (ModelState.IsValid)
            {
                ServiceClient service = new ServiceClient();
                var output = service.AddDomain(DomainMapper.ModelToDto(inputModel));
                var listDisplay = PrepareRetrunFromOperation(new ListDomainModel(), output.Data, output.Status,
                                  Utilities.MessageUtil.GetMessage(Operation.Add, output.Status));


                // เพิ่ม message แสดงในหน้าแม่
                TempData["DomainMessage"] = listDisplay.Message;
                TempData["DomainStatus"] = output.Status;
                if (output.Data != null)
                {
                    TempData["DomainId"] = output.Data.Id;
                }
                return View("ListDomain", listDisplay);
            }
            else
            {
                SetupRegisterViewModel(inputModel);
                return View(inputModel);
            }
        }

        [HttpPost]
        public string DeleteDomains(string[] DomainCheckbox)
        {
            ListDomainModel input = new ListDomainModel();
            if (ModelState.IsValid)
            {
                input = Delete(DomainCheckbox, input);
            }

            if (input.IsSuccessed.GetValueOrDefault(false))
                return Boolean.TrueString;
            else
                return Boolean.FalseString;
        }

        [HttpPost]
        public String DeleteDomainById(string Id)
        {
            List<string> delList = new List<string>();
            delList.Add(Id);
            ServiceClient service = new ServiceClient();
            var output = service.DeleteDomain(delList);

            if (output.Status)
            {
                foreach (string delListID in delList)
                {
                    if (System.IO.Directory.Exists(Server.MapPath("~/Image/Domain") + "\\" + delListID + "\\"))
                    {
                        System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(Server.MapPath("~/Image/Domain") + "\\" + delListID + "\\"); DI.Delete(true);
                    }
                }
            }

            //แสดง message ให้ class แม่
            TempData["DomainMessage"] = Utilities.MessageUtil.GetMessage(Operation.Delete, output.Status);
            TempData["DomainStatus"] = output.Status;

            if (output.Status)
                return Boolean.TrueString;
            else
                return Boolean.FalseString;

        }

        // Check does DomainName exist
        [HttpPost]
        public JsonResult doesDomainNameExist(string DomainName, string Mode, string OldValue)
        {
            bool callCheck = false;
            if (Mode.Equals("Add", StringComparison.OrdinalIgnoreCase))
            {
                callCheck = true;
            }
            else if (Mode.Equals("Edit", StringComparison.OrdinalIgnoreCase))
            {
                if (!OldValue.Trim().Equals(DomainName.Trim(), StringComparison.OrdinalIgnoreCase))
                    callCheck = true;
            }

            if (callCheck)
            {
                var service = new ServiceClient();
                var exist = service.ExistDomain(DomainName).Data;
                return Json(!exist);
            }
            else
                return Json(true);
        }

        #region private methods

        private ListDomainModel Delete(string[] inputList, ListDomainModel input)
        {
            List<string> delList = new List<string>();
            var listDisplay = new ListDomainModel();
            if (inputList != null && inputList.Length > 0)
            {
                foreach (string id in inputList)
                {
                    delList.Add(id);
                }
                ServiceClient service = new ServiceClient();
                var output = service.DeleteDomain(delList);
                listDisplay = PrepareRetrunFromOperation(input, output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Delete, output.Status));

                if (output.Status)
                {
                    foreach (string inputListSplit in inputList)
                    {
                        if (System.IO.Directory.Exists(Server.MapPath("~/Image/Domain") + "\\" + inputListSplit + "\\"))
                        {
                            System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(Server.MapPath("~/Image/Domain") + "\\" + inputListSplit + "\\"); DI.Delete(true);
                        }
                    }
                }

                TempData["DomainMessage"] = listDisplay.Message;
                TempData["DomainStatus"] = output.Status;
            }

            listDisplay.ListItems = PrepareSearch(listDisplay);
            return listDisplay;
        }

        private List<DomainModel> PrepareSearch(ListDomainModel input)
        {

            GetAllDomainRequestModel searchInputs = new GetAllDomainRequestModel()
            {
                DomainName = (input.DomainNameSearch == null) ? "" : input.DomainNameSearch,

                Sort = "DomainName",
                SortType = sType.ASC
            };
            var result = Search(searchInputs);
            return result.List;
        }

        private GetAllResponseModel<DomainModel> Search(GetAllDomainRequestModel input)
        {
            ServiceClient service = new ServiceClient();
            GetAllDomainRequestDto gAllreq = new GetAllDomainRequestDto
            {
                DomainName = input.DomainName,
                SortType = input.SortType.ToString(),
                Sort = input.Sort
            };
            var response = service.GetAllDomain(gAllreq);
            var result = new GetAllResponseModel<DomainModel>();
            result.List = new List<DomainModel>();
            if (response != null)
            {
                if (response.Data != null && response.Data.Count > 0)
                {
                    foreach (DomainDto responseDTO in response.Data)
                    {
                        DomainModel resultModel = null;
                        DomainDto tempDto = responseDTO;
                        resultModel = DomainMapper.DtoToModel(tempDto);
                        result.List.Add(resultModel);
                    }
                }
            }
            return result;
        }

        private ListDomainModel PrepareRetrunFromOperation(ListDomainModel listModel, DomainDto dto, bool status, string message)
        {
            if (status)
            {
                if (dto != null)
                {
                    listModel.ListItems.Add(DomainMapper.DtoToModel(dto));
                }
            }
            listModel.Message = message;
            listModel.IsSuccessed = status;
            return listModel;

        }




        private GetAllResponseModel<FunctionModel> SearchFunctions_Function(GetAllFunctionRequestModel input)
        {
            ServiceClient service = new ServiceClient();
            int domainId;
            int.TryParse(input.DomainId, out domainId);
            GetAllFunctionRequestDto gAllreq = new GetAllFunctionRequestDto
            {
                DomainId = domainId,
                FuncName = input.FuncName,

                Sort = input.Sort,
                SortType = input.SortType.ToString(),
            };
            var response = service.GetAllFunction(gAllreq);
            var result = new GetAllResponseModel<FunctionModel>();
            result.List = new List<FunctionModel>();
            if (response != null)
            {
                if (response.Data != null && response.Data.Count > 0)
                {
                    foreach (FunctionDto responseDTO in response.Data)
                    {
                        FunctionModel resultModel = null;
                        FunctionDto tempDto = responseDTO;
                        resultModel = FunctionMapper.DtoToModel(tempDto);
                        result.List.Add(resultModel);
                    }
                }
            }
            return result;
        }

        private List<FunctionModel> PrepareFunctions_FunctionSearch(int domainId)
        {
            ServiceClient service = new ServiceClient();
            GetAllFunctionRequestDto gAllreq = new GetAllFunctionRequestDto
            {
                DomainId = domainId
            };
            var response = service.GetAllFunction(gAllreq);
            var result = new GetAllResponseModel<FunctionModel>();
            result.List = new List<FunctionModel>();
            if (response != null)
            {
                if (response.Data != null && response.Data.Count > 0)
                {
                    foreach (FunctionDto responseDTO in response.Data)
                    {
                        FunctionModel resultModel = null;
                        FunctionDto tempDto = responseDTO;
                        resultModel = FunctionMapper.DtoToModel(tempDto);
                        result.List.Add(resultModel);
                    }
                }
            }
            return result.List;
        }


        private void SetupRegisterViewModel(DomainModel model)
        {
            //เช็คว่ามี Attribute ที่เป็น DateTime ใน model หรือเปล่าถ้ามี + ปีไป 543 ถ้าปีเป็น ค.ศ.
            Utilities.Utilities.PrepareDateTimeProperity(model);
        }

        /// <summary>
        /// Name ::: Mr. Akawit Tangkupatanonth
        /// Date ::: 16/03/2014
        /// Description ::: This function for call validate method in validate class
        /// </summary>
        /// <returns>Boolean</returns>

        #endregion
    }
}
